package com.src.computec.gestion.carguegestion.portlet;

import com.src.computec.gestion.carguegestion.dto.ArchivoDto;
import com.src.computec.gestion.carguegestion.exception.CargueGestionException;
import com.src.computec.gestion.carguegestion.source.CargueGestionSource;
import com.src.computec.gestion.carguegestion.utilidades.ConstantesGenerales;
import com.src.computec.radar.base.ldap.dto.LdapUserDto;
import com.src.computec.radar.base.ldap.exception.LdapException;
import com.src.computec.radar.base.source.CoreSource;
import com.src.computec.radar.services.utilities.consultas.delegate.ConsultasDelegate;
import com.src.computec.radar.services.utilities.consultas.exception.ConsultasException;
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.UnavailableException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.portlet.PortletFileUpload;

/**
 * The class provides a default implementation
 * for the <code>Portlet</code> interface.<p>
 *
 * It is recommended not to extend the Portlet interface directly.
 * Rather, a portlet should derive from this or any other derived
 * class and use the provided helper methods for the different modes.
 */
public class UploadPortlet extends GenericPortlet {
    private PortletContext myPortletContext;
    private ConstantesGenerales contantesGenerales = ConstantesGenerales.getInstance();
    
    public void init(PortletConfig config) throws PortletException, UnavailableException {
        super.init(config);
        myPortletContext = config.getPortletContext();
    }
    
    public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException 
    {
        FileItemFactory factory = new DiskFileItemFactory();
        PortletFileUpload upload = new PortletFileUpload(factory);
        
        CargueGestionSource cargueGestionSource = CargueGestionSource.getInstance();
        
        LdapUserDto ldapUser = (LdapUserDto)request.getPortletSession().getAttribute(ConstantesGenerales.LDAP_USER_SESSION);
        
        try 
        {
            if(ldapUser == null) 
            {
                ldapUser = this.findUserLdap(request);               
            }        
        
            List items = upload.parseRequest(request);
            
            Iterator iter = items.iterator();
            
            while (iter.hasNext()) 
            {
                FileItem item = (FileItem) iter.next();
                
                if (item.isFormField()) 
                {
                } 
                else 
                {
                    request.getPortletSession().setAttribute(ConstantesGenerales.ERROR_SESSION, "");
                    
                    ArrayList lista = (ArrayList)request.getPortletSession().getAttribute(ConstantesGenerales.LISTA_SESSION);
                    
                    if( lista == null) 
                    {
                        lista = new ArrayList();
                        request.getPortletSession().setAttribute(ConstantesGenerales.LISTA_SESSION, lista);
                    }
                    
                    if( !item.getName().equals("") ) 
                    {
                        ArchivoDto dto = new ArchivoDto();
                        dto.setCompletado(false);
                        dto.setEnCola(false);
                        dto.setId(new Long(ConstantesGenerales.CONTADOR));
                        dto.setRegistrosActuales(0);
                        dto.setTotalRegistros(0);
                        dto.setIdUser(ldapUser.getIdLdap());
                        dto.setCodigoProveedor( (String)request.getPortletSession().getAttribute(ConstantesGenerales.CODIGO_PROVEEDOR_SESSION) );
                        dto.setNombreArchivo(item.getName());
                        
                        processUploadedFile(item,ConstantesGenerales.CONTADOR, dto.getIdUser(), dto.getCodigoProveedor());
                        
                        Long cont = new Long(dto.getId());
                        ConstantesGenerales.TABLA_ARCHIVOS.put(cont,dto);
                        lista.add(cont);
                        request.getPortletSession().setAttribute(ConstantesGenerales.LISTA_SESSION, lista);
                        
                        ConstantesGenerales.CONTADOR++;
                        
                        if(ConstantesGenerales.CONTADOR > ConstantesGenerales.TOP_CONTADOR) 
                        {
                            ConstantesGenerales.CONTADOR = 0;
                        }
                    } 
                    else 
                    {
                        request.getPortletSession().setAttribute(ConstantesGenerales.ERROR_SESSION, cargueGestionSource.getCargueGestionErrorSetupKey("SeleccionArchivo"));
                    }
                }
            }
            
        } 
        catch (ConsultasException ex) {
            request.getPortletSession().setAttribute(ConstantesGenerales.ERROR_SESSION, cargueGestionSource.getCargueGestionErrorSetupKey("ErrorSistema"));
            ex.printStackTrace();
        } 
        catch (FileUploadException ex) {
            request.getPortletSession().setAttribute(ConstantesGenerales.ERROR_SESSION, cargueGestionSource.getCargueGestionErrorSetupKey("ErrorLectura"));
            ex.printStackTrace();
        } 
        catch (CargueGestionException ex) {
            request.getPortletSession().setAttribute(ConstantesGenerales.ERROR_SESSION, cargueGestionSource.getCargueGestionErrorSetupKey("ErrorLectura"));
            ex.printStackTrace();
        }
    }    
    
    protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException 
    {
        request.setAttribute("viewParam", "view");        
        processPage(request, response, "viewPage");
    }
    
    protected void doEdit(RenderRequest request, RenderResponse response) throws PortletException, IOException {
        request.setAttribute("editParam", "edit");
        processPage(request, response, "editPage");
    }
    
    protected void doHelp(RenderRequest request, RenderResponse response) throws PortletException, IOException {
        processPage(request, response, "helpPage");
    }
    
    private void processPage(RenderRequest request, RenderResponse response, String page) throws PortletException, IOException {
        response.setContentType(request.getResponseContentType());
        String value = request.getPreferences().getValue(page, "");
        
        if (value != null && value.length() > 0) {
            myPortletContext.getRequestDispatcher(value).include(request, response);
        }
    }
    
    /**
     * Metodos Anexos al portlet
     */
    private void processUploadedFile(FileItem item, Long cont, String idUser, String codigoProveedor) throws CargueGestionException {
        try 
        {
            String nombreUploadFile = ConstantesGenerales.FILE_PREFIX + cont.toString() + ConstantesGenerales.SPLIT_PARAM + idUser + ConstantesGenerales.SPLIT_PARAM + codigoProveedor + ConstantesGenerales.EXTENSION;
            File uploadedFile = new File(ConstantesGenerales.FOLDER_CARGUE_ARCHIVOS + ConstantesGenerales.PATH_ARCHIVOS + nombreUploadFile);
            
            item.write(uploadedFile);
        } catch(Exception e) {
            throw new CargueGestionException("UploadPortlet: processAction: processUploadedFile: " + e.toString(), e);
        }
    }
    
    private String getUIdByDomainName(String domainName) {
        String[] tokens =  domainName.split(",");
        
        if(tokens.length > 0) {
            String[] uIdTokens = (tokens[0]).split("=");
            
            if(uIdTokens.length == 2) {
                return uIdTokens[1];
            }
        }
        return "";
    }
    
    private LdapUserDto findUserLdap(ActionRequest request) throws ConsultasException
    {
        ConsultasDelegate ldapDelegate = new ConsultasDelegate();    
        
        LdapUserDto ldapUser = new LdapUserDto(); 
        //ldapUser.setIdLdap( "jlperea.computec" );
        ldapUser.setIdLdap( this.getUIdByDomainName(request.getRemoteUser()) );
        ldapUser = ldapDelegate.getLdapUserByPrimaryKey(ldapUser);
        
        String codigoProveedor = ConstantesGenerales.CODIGO_PROVEEDOR_COMPUTEC;
        
        Iterator iterRoles = ldapUser.getRoles().iterator();
        
        while(iterRoles.hasNext())
        {
            String nombreRoleAux = (String)iterRoles.next();
            if( nombreRoleAux.compareToIgnoreCase( CoreSource.getInstance().getLdapSetupKey( "ldap_rol_empresa_mensajeria_cn" ) ) == 0 )
            {
                codigoProveedor = ldapUser.getCodigoEmpresaMensajeria();           
            }            
        } 
        
        request.getPortletSession().setAttribute(ConstantesGenerales.LDAP_USER_SESSION, ldapUser); 
        request.getPortletSession().setAttribute(ConstantesGenerales.CODIGO_PROVEEDOR_SESSION, codigoProveedor);
        
        return ldapUser;
    }
}
